<template>
  <view class="home">
    <view class="header">
      <view class="header__title-box">
        <text class="header__title-box__text">你好</text>
        <text class="header__title-box__text">{{ nickName }}</text>
      </view>
      <view class="score-list">
        <view class="current-score" @tap="goToPoint">
          <view class="icon-coins"></view>
          <text>{{ totalScore }}</text>
        </view>
        <view
          v-for="(taskRecord, index) in taskList"
          :key="index"
          class="score-card"
          :style="`background-image: url(${
            taskRecord.task.imageUrl || testImage
          })`"
          @tap="showSignTaskDialog(taskRecord)"
        >
          <text class="score-card__title">{{ taskRecord.task.title }}</text>
          <view class="score-card__content">
            <view class="icon-coins"></view>
            <text>{{ taskRecord.task.score }}</text>
          </view>
        </view>
        <view
          class="score-card score-card--add-bg all-list"
          @tap="navigateTaskList"
        >
          <text class="score-card__title">所有任务</text>
          <view class="score-card__content">
            <text
              >{{ allTaskList.length - taskList.length }}/{{
                allTaskList.length
              }}</text
            >
          </view>
        </view>
      </view>
    </view>
    <view class="questionnaire-entry" @tap="gotoQuestionnaire()">
      <view class="home-question-title">
        完成健康评估立即获取完整的健康管理方案
      </view>
      <view class="container">
        <view class="left">
          <view class="home-question-items">
            <view
              class="home-question-item"
              v-for="questionnaire in questionnaires"
              :key="questionnaire.id"
            >
              {{ questionnaire.title }}
            </view>
          </view>
        </view>
        <view class="right">
          <view class="rightIcon">
            <view class="at-icon at-icon-chevron-right arrow" />
          </view>
        </view>
      </view>
    </view>
    <view class="target-list">
      <view
        v-for="(item, index) in targetList"
        :key="index"
        class="target-card"
        @tap="item.onClick()"
      >
        <text class="title">{{ item.title }}</text>
        <text class="value">{{ item.value }}</text>
        <text class="notes" :class="item.isWaring ? '.waring' : ''"
          >{{ item.notes || "" }}
        </text>
      </view>
    </view>
    <view class="recommend-training">
      <view class="title">
        <image
          class="at-icon title-icon"
          src="https://manbingguanli.oss-cn-beijing.aliyuncs.com/wenduo/cb4e2c54536245cc80534f0b71c56f1f运动健身.png"
        />
        <view> 推荐训练营</view>
      </view>
      <swiper autoplay interval="3000">
        <swiper-item v-for="item in carousels" :key="item.id">
          <view class="carousel">
            <image :src="item.src" @tap="goPlan(item.planName)" />
          </view>
        </swiper-item>
      </swiper>
    </view>
    <view class="health-data">
      <view class="title">
        <image
          class="at-icon title-icon"
          src="https://manbingguanli.oss-cn-beijing.aliyuncs.com/wenduo/a582c936c9b649f2a23f0b869ffac7cb健康计划.png"
        />
        <view> 我的健康数据</view>
      </view>
      <view
        v-for="(item, index) in healthList"
        :key="index"
        class="health-card"
        @tap="item.onClick()"
      >
        <text class="card-title">{{ item.title }}</text>
        <text class="card-value">{{ item.value }}</text>
        <text class="value-unit">{{ item.unit }}</text>
      </view>
    </view>
    <view class="divider"></view>
    <!-- TODO: 打卡任务内容组件抽取 -->
    <at-modal :isOpened="isOpenDialog" :onClose="handleClose">
      <at-modal-content>
        <view v-if="taskDialogData" class="task-dialog-content">
          <text class="title">{{ taskDialogData.task.title }}</text>
          <text class="point">+{{ taskDialogData.task.score }}积分</text>
          <image
            class="task-modal-image"
            :src="taskDialogData.task.imageUrl || testImage"
          />
        </view>
      </at-modal-content>
      <at-modal-action>
        <button
          v-if="taskDialogData"
          class="complete-btn"
          @tap="completeTask(taskDialogData.id)"
        >
          我做到了
        </button>
      </at-modal-action>
    </at-modal>
  </view>
</template>

<script lang="ts">
import "./index.less";
import Taro from "@tarojs/taro";
import { AtModal, AtModalContent, AtModalAction } from "taro-ui-vue";
import { getDailyTaskList, checkMarkTask } from "../../services/task-service";
import { getEncryptedData } from "../../services/user-service";
import { allCompletedTests } from "../../services/healthy-test-service";

import {
  getUserProfileDataToday,
  updateSteps,
} from "../../services/healthy-data-service";
import get from "lodash.get";
import findIndex from "lodash.findindex";
import last from "lodash.last";
import testImage from "../../assets/images/tasktest.jpg";

import { healthy } from "../../apis";
import { request } from "../../services/http-base";

export default {
  components: {
    atModal: AtModal,
    atModalContent: AtModalContent,
    atModalAction: AtModalAction,
  },
  data() {
    return {
      carousels: [
        {
          id: 1,
          planName: "01.高血糖管理服务30天降糖详情页",
          src: "https://manbingguanli.oss-cn-beijing.aliyuncs.com/wenduo/df2d59bd1e3647eab2a85c96c6b04fbc01.高血糖管理服务30天降糖主图-2 - 副本.jpg",
        },
        {
          id: 2,
          planName: "02.高血脂管理服务30天降血脂详情页",
          src: "https://manbingguanli.oss-cn-beijing.aliyuncs.com/wenduo/5ac4b1c8a53749c49b96d5c9bccf398102.高血脂管理服务30天降血脂主图-2 - 副本.jpg",
        },
        {
          id: 3,
          planName: "03.健康减重管理服务30天赶走小肚腩详情页",
          src: "https://manbingguanli.oss-cn-beijing.aliyuncs.com/wenduo/c8f3202ff6bd47c698a3a3c4a924e37903.健康减重管理服务30天赶走小肚腩主图-2 - 副本.jpg",
        },
        {
          id: 4,
          planName: "04.高血压管理服务30天降血压详情页",
          src: "https://manbingguanli.oss-cn-beijing.aliyuncs.com/wenduo/bfc335b823d84effb168127027504d9504.高血压管理服务30天降血压主图-2 - 副本.jpg",
        },
      ],
      questionnaires: [],
      targetList: [
        {
          name: "bmi",
          title: "BMI指数",
          value: "28.5",
          notes: "偏胖",
          isWaring: true,
          onClick: () => {
            Taro.navigateTo({
              url: "/pages/health-data/weight/index",
            });
          },
        },
        {
          name: "weight",
          title: "体重",
          value: "63",
          notes: "kg",
          onClick: () => {
            Taro.navigateTo({
              url: "/pages/health-data/weight/index",
            });
          },
        },
        {
          name: "calorie",
          title: "卡路里消耗",
          value: "1234",
          notes: "cal",
          onClick: () => {
            Taro.navigateTo({
              url: "/pages/health-data/steps/index",
            });
          },
        },
        {
          name: "steps",
          title: "步数",
          value: "--",
          onClick: () => {
            Taro.navigateTo({
              url: "/pages/health-data/steps/index",
            });
          },
        },
      ],
      taskList: [],
      allTaskList: [],
      isOpenDialog: false,
      taskDialogData: null,
      bloodPressuresToday: {
        title: "血压",
        value: "--",
        unit: "mmHg",
        onClick: () => {},
      },
      bloodSugarsToday: {
        title: "血糖",
        value: "--",
        unit: "mmHg",
        onClick: () => {},
      },
      sleepToday: {
        title: "睡眠",
        value: "--",
        unit: "mmHg",
        onClick: () => {},
      },
      heartBeatToday: {
        title: "心率",
        value: "--",
        unit: "mmHg",
        onClick: () => {},
      },
      bloodFatToday: {
        title: "血脂",
        value: "--",
        unit: "",
        onClick: () => {},
      },
      renal: {
        title: "肾功",
        value: "--",
        unit: "",
        onClick: () => {},
      },
      todayData: {},
      testImage,
    };
  },
  computed: {
    nickName: function () {
      // TODO: 此处暂用用户手动输入的名字，后期授权流程更改后，使用用户的微信昵称
      return this.$store.state.user.userInfo.nickName || '微信用户';
    },
    totalScore: function () {
      return get(this.todayData, "totalScore", "--");
    },
    healthList: function () {
      return [
        this.bloodPressuresToday,
        this.bloodSugarsToday,
        this.bloodFatToday,
        this.renal,
      ];
    },
  },
  methods: {
    goToPoint() {
      Taro.navigateTo({
        url: `/pages/sales/points/index`,
      });
    },
    goPlan(planName) {
      Taro.navigateTo({ url: `/pages/plan/index?planName=${planName}` });
    },
    gotoQuestionnaire() {
      Taro.navigateTo({
        url: "/pages/health-questionnaire/entry/index",
      });
    },
    async getTotalScore() {},
    async getTaskList() {},
    async getPersonalHealthyData() {},
    gotoTaskBrief() {
      Taro.navigateTo({
        url: "",
      });
    },
    getGoalsData() {},
    getStepsFromWx() {
      Taro.getWeRunData({
        success: async (res) => {
          // 拿 encryptedData 到开发者后台解密开放数据
          const encryptedData = res["encryptedData"];
          const iv = res["iv"];
          let steps = await getEncryptedData(encryptedData, iv);
          let stepsList = get(steps, "data.data.stepInfoList", [{ step: 0 }]);
          let latestSteps = last(stepsList).step;
          let stepsCardConfigIndex = findIndex(
            this.targetList,
            (target: { name: string }) => target.name === "steps"
          );
          this.targetList[stepsCardConfigIndex].value = latestSteps;
          updateSteps({
            calorie: 10,
            distance: 10,
            stepCount: latestSteps,
          });
        },
      });
    },
    navigateTaskList() {
      Taro.navigateTo({
        url: "/pages/tasks/index/index",
      });
    },
    async getTodayTaskList() {
      const todayTaskList = await getDailyTaskList();
      this.allTaskList = todayTaskList;
      this.taskList = todayTaskList.filter(
        (taskRecord) => !taskRecord.finished
      );
    },
    showSignTaskDialog(taskRecord) {
      this.taskDialogData = taskRecord;
      this.isOpenDialog = true;
    },
    handleClose() {
      this.isOpenDialog = false;
    },
    async completeTask(taskRecordId: number) {
      const res = await checkMarkTask(taskRecordId);
      if (res.data.code === "success") {
        this.isOpenDialog = false;
        await this.getTodayTaskList();
      }
    },
    refresh() {
      this.getTodayTaskList();
      this.loadQuestionList();
      this.getTodayData();
      this.checkTask();
    },
    async getTodayData() {
      let result = await getUserProfileDataToday();
      this.$set(
        this.todayData,
        "customerProfile",
        get(result, "data.data.bodyProfile")
      );
      console.log(result);
      this.todayData = get(result, "data.data");
      this.setBMI();
      this.setWeight();
      this.setCalories();
      this.setBloodPressure();
      this.setBloodSugar();
      this.setSleep();
      this.setBloodFat();
      this.setRenal();
    },
    setRenal() {
      this.renal = {
        name: "renal",
        title: "尿酸",
        value: ``,
        unit: `点击查看`,
        onClick: () => {
          Taro.navigateTo({
            url: "/pages/health-data/renal/index",
          });
        },
      };
    },
    setBMI() {
      let bmi = get(this.todayData, "bodyProfile.bmi", 0);
      console.log(this.todayData);
      let index = findIndex(this.targetList, (target) => target.name === "bmi");
      this.targetList[index].value = bmi;
      if (isNaN(bmi)) {
        this.targetList[index].notes = "--";
        return;
      }
      if (bmi < 18.5) {
        this.targetList[index].notes = "偏瘦";
        this.targetList[index].isWaring = true;
        return;
      }
      if (18.5 <= bmi && bmi <= 23.9) {
        this.targetList[index].notes = "正常";
        return;
      } else {
        this.targetList[index].notes = "偏胖";
        this.targetList[index].isWaring = true;
        return;
      }
    },
    setWeight() {
      let weight = get(this.todayData, "bodyProfile.weight", "--");
      let index = findIndex(
        this.targetList,
        (target) => target.name === "weight"
      );
      this.targetList[index].value = weight == "--" ? "" : weight;
      this.targetList[index].unit = weight == "--" ? "点击添加数据" : "kg";
    },
    setCalories() {
      let calorie = Math.floor(
        (get(this.todayData, "bodyProfile.steps.stepCount", 0) * 0.75 * 47) /
          1000
      );
      let index = findIndex(
        this.targetList,
        (target) => target.name === "calorie"
      );
      this.targetList[index].value = calorie;
    },
    setBloodPressure() {
      console.log("todayDataHome", this.todayData);
      let item = get(this.todayData, "bodyProfile.bloodPressures[0]", {
        systolicPressure: undefined,
        diastolicPressure: undefined,
      });
      this.bloodPressuresToday = {
        name: "bloodPressure",
        title: "血压",
        value:
          item.systolicPressure == undefined
            ? ""
            : `${item.systolicPressure}/${item.diastolicPressure}`,
        unit: item.systolicPressure == undefined ? "点击添加数据" : "mmHg",
        onClick: () => {
          Taro.navigateTo({
            url: "/pages/health-data/blood-pressure/index",
          });
        },
      };
    },
    setBloodSugar() {
      let allBloodSugars =
        get(this.todayData, "bodyProfile.bloodSugars", []) || [];
      let latestKongfuBloodSugarsIndex = findIndex(
        allBloodSugars,
        (item) => item.mealPeriod === 0
      );
      let latestAfter2HrsBloodSugarsIndex = findIndex(
        allBloodSugars,
        (item) => item.mealPeriod === 13
      );
      let latestKongfuBloodSugars = get(
        allBloodSugars,
        `${latestKongfuBloodSugarsIndex}`,
        { glucoseConcentration: "--" }
      );
      let latestAfter2HrsBloodSugars = get(
        allBloodSugars,
        `${latestAfter2HrsBloodSugarsIndex}`,
        { glucoseConcentration: "--" }
      );
      this.bloodSugarsToday = {
        name: "bloodSugar",
        title: "血糖（空腹/餐后2小时）",
        value:
          latestKongfuBloodSugars.glucoseConcentration == "--"
            ? ""
            : `${latestKongfuBloodSugars.glucoseConcentration}/${latestAfter2HrsBloodSugars.glucoseConcentration}`,
        unit:
          latestKongfuBloodSugars.glucoseConcentration == "--"
            ? "点击添加数据"
            : "mmol/L",
        onClick: () => {
          Taro.navigateTo({
            url: "/pages/health-data/blood-sugar/index",
          });
        },
      };
    },
    setSleep() {
      let item = get(this.todayData, "bodyProfile.sleep", {
        totalTime: "--",
      }) || { totalTime: "--" };
      this.sleepToday = {
        name: "sleep",
        title: "睡眠数据",
        value: `${item.totalTime || " -- "}`,
        unit: "Hours",
        onClick: () => {
          Taro.navigateTo({
            url: "/pages/health-data/sleep/index",
          });
        },
      };
    },
    setHeartBeat() {
      let item = get(this.todayData, "bodyProfile.heartRate", {
        slowHeartRate: "--",
        fastHeartRate: "--",
      }) || { slowHeartRate: "--", fastHeartRate: "--" };
      this.heartBeatToday = {
        name: "heartBeat",
        title: "心率",
        value: `${item.slowHeartRate}/${item.fastHeartRate}`,
        unit: "BPM",
        onClick: () => {
          Taro.navigateTo({
            url: "/pages/health-data/heart-beat/index",
          });
        },
      };
    },
    setBloodFat() {
      this.bloodFatToday = {
        name: "bloodFat",
        title: "血脂",
        value: "",
        unit: `点击查看`,
        onClick: () => {
          Taro.navigateTo({
            url: "/pages/health-data/blood-lipids/index",
          });
        },
      };
    },
    async checkTask() {
      const isCompletedTask = await allCompletedTests();
      console.log("isCompletedTask", isCompletedTask);
    },
    async loadQuestionList() {
      let result = await request(healthy);
      this.questionnaires = result.data.data.pages;
      this.$store.commit("setQuestionnaires", this.questionnaires);
    },
  },
  async created() {
    this.getStepsFromWx();
    await this.getTodayTaskList();
    await this.getTodayData();
    await this.checkTask();
  },
  async mounted() {
    await this.loadQuestionList();
  },

  // onLoad
  onLoad() {},

  // onReady
  onReady() {},

  // 对应 onShow
  onShow() {},

  // 对应 onHide
  onHide() {},

  // 对应 onPullDownRefresh
  onPullDownRefresh() {},
};
</script>
